package com.autonavi.yunda.yunji.core.engine.argresolver;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.enums.ParamType;
import com.autonavi.yunda.yunji.core.vo.HttpRequest;
import com.autonavi.yunda.yunji.core.vo.param.Param;
import org.springframework.beans.SimpleTypeConverter;

/**
 * 参数类型解析器
 *
 * @author cizhong.wcs
 * @date 2022/6/1 21:05
 */
public interface ParamResolver {
    boolean supportsParam(Param param);

    Object resolve(HttpRequest request, Param param);

    static Object getParamValueByType(Object value, String type) {
        try {
            if (value == null) {
                return null;
            }
            ParamType paramType = ParamType.fromCode(type);
            if (ParamType.FILE.getCode().equals(type)) {
                return value;
            } else if (ParamType.OBJECT.getCode().equals(type) || ParamType.ARRAY.getCode().equals(type)) {
                if (value instanceof String) {
                    return JsonUtils.from(value.toString(), Object.class);
                } else {
                    return value;
                }
            } else {
                if (ParamType.STRING.getCode().equals(type) && !(value instanceof String)) {
                    return JsonUtils.toString(value);
                }
                SimpleTypeConverter simpleTypeConverter = new SimpleTypeConverter();
                return simpleTypeConverter.convertIfNecessary(value, paramType.getType());
            }
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_WARN, "参数类型转换异常type = " + type + ", value = " + JsonUtils.toString(value), e);
        }

    }
}
